package com.ruoyi.web.controller.pay;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.JwtUtil;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.pay.config.GoodsConstant;
import com.ruoyi.pay.config.PayConfigParmaInitRunner;
import com.ruoyi.pay.entity.PayGoodsOrder;
import com.ruoyi.pay.service.PayGoodsOrderService;
import com.ruoyi.pay.utils.PayConstants;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 商品订单Controller
 *
 * @author ruoyi
 * @date 2020-10-10
 */
@Controller
@RequestMapping("/system/goodsorder")
public class PayGoodsOrderController extends BaseController {
    private String prefix = "system/goodsorder";

    @Autowired
    private PayGoodsOrderService payGoodsOrderService;

    /**
     * 商品订单
     *
     * @param goods        商品
     * @param modelAndView
     * @return R
     */
    @GetMapping("/buy")
    public ModelAndView buy(@Valid PayGoodsOrder goods, BindingResult result, HttpServletRequest request, ModelAndView modelAndView) {

        String token = request.getParameter("token"); // 从 http 请求头中取出
        // 验证 token
        if (!JwtUtil.verify(token, goods.getUserId())) {
            throw new BusinessException("用户登录失效,请重新登录");
        }
        // 验证字段是否符合规则
        if (result.hasErrors()) {
            throw new BusinessException(result.getFieldError().getDefaultMessage());
        }
        goods.setGoodsOrderId(IdWorker.getId(goods));
        GoodsConstant.Goods goods1 = null;
        try {
            goods1 = GoodsConstant.Goods.valueOf("ID_" + goods.getGoodsId());
        } catch (IllegalArgumentException e) {
           throw  new BusinessException("商品不存在");
        }
        goods.setGoodsName(goods1.getName());
       BigDecimal multiply = new BigDecimal(goods1.getAmount()).multiply(new BigDecimal(goods.getNumber()));

        goods.setAmount(multiply.toString());

        String ua = request.getHeader(HttpHeaders.USER_AGENT);
        if (ua.contains(PayConstants.MICRO_MESSENGER)) {
            throw  new BusinessException("请使用支付宝扫码支付");
           // String appId = WxPayApiConfigKit.getWxPayApiConfig().getAppId();
           // modelAndView.setViewName("redirect:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId +
           //         "&redirect_uri=http%3a%2f%2fadmin.pig4cloud.com%2fpay%2fgoods%2fwx%3famount%3d" + goods.getAmount() +
           //         "&response_type=code&scope=snsapi_base&state=" + appId);
           // return modelAndView;
        }

        modelAndView.setViewName(  prefix + "/pay");
        modelAndView.addAllObjects(payGoodsOrderService.buy(goods));
        return modelAndView;
    }
    @SneakyThrows
    @GetMapping("/test")
    @ResponseBody
    public String test(String id) {
        PayGoodsOrder byId = payGoodsOrderService.getById(id);
        payGoodsOrderService.confirmOrder(byId);
        return "1";
    }



    /**
     * oauth
     *
     * @param goods        商品信息
     * @param state        appid
     * @param code         回调code
     * @param modelAndView
     * @return
     * @throws WxErrorException
     */
    @SneakyThrows
    @GetMapping("/wx")
    public ModelAndView wx(PayGoodsOrder goods, String state, String code, ModelAndView modelAndView) {
        WxMpService wxMpService = PayConfigParmaInitRunner.mpServiceMap.get(state);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        goods.setUserId(wxMpOAuth2AccessToken.getOpenId());
        goods.setAmount(goods.getAmount());
        modelAndView.setViewName("pay");
        modelAndView.addAllObjects(payGoodsOrderService.buy(goods));
        return modelAndView;
    }

    @RequiresPermissions("system:order:view")
    @GetMapping()
    public String order() {
        return prefix + "/goodsorder";
    }

    /**
     * 查询商品订单列表
     */
    @RequiresPermissions("system:order:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PayGoodsOrder payGoodsOrder) {
        startPage();
        List<PayGoodsOrder> list = payGoodsOrderService.list(Wrappers.query(payGoodsOrder));
        return getDataTable(list);
    }

    /**
     * 导出商品订单列表
     */
    @RequiresPermissions("system:order:export")
    @Log(title = "商品订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(PayGoodsOrder payGoodsOrder) {
        List<PayGoodsOrder> list = payGoodsOrderService.list(Wrappers.query(payGoodsOrder));
        ExcelUtil<PayGoodsOrder> util = new ExcelUtil<PayGoodsOrder>(PayGoodsOrder.class);
        return util.exportExcel(list, "order");
    }

    /**
     * 新增商品订单
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存商品订单
     */
    @RequiresPermissions("system:order:add")
    @Log(title = "商品订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(PayGoodsOrder payGoodsOrder) {
        return toAjax(payGoodsOrderService.save(payGoodsOrder));
    }

    /**
     * 修改商品订单
     */
    @GetMapping("/edit/{goodsOrderId}")
    public String edit(@PathVariable("goodsOrderId") Long goodsOrderId, ModelMap mmap) {
        PayGoodsOrder payGoodsOrder = payGoodsOrderService.getById(goodsOrderId);
        mmap.put("payGoodsOrder", payGoodsOrder);
        return prefix + "/edit";
    }

    /**
     * 修改保存商品订单
     */
    @RequiresPermissions("system:order:edit")
    @Log(title = "商品订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(PayGoodsOrder payGoodsOrder) {
        return toAjax(payGoodsOrderService.updateById(payGoodsOrder));
    }

    /**
     * 删除商品订单
     */
    @RequiresPermissions("system:order:remove")
    @Log(title = "商品订单", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(payGoodsOrderService.removeByIds(Arrays.asList(ids.split(","))));
    }
}
